package com.wangzhixuan.commons.base;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.PropertiesLoader;
import com.wangzhixuan.commons.utils.StringEscapeEditor;
import com.wangzhixuan.model.Dictionary;
import com.wangzhixuan.model.User;
import com.wangzhixuan.service.IDictionaryService;
import com.wangzhixuan.service.IUserService;

/**
 * Api 基础controller
 * Created by GTE on 2017/4/17.
 */
public abstract class ApiBaseController {
	
    @Autowired
    private IDictionaryService dictionaryService;
    
    @Autowired
    private IUserService userService;
    
    // 控制器本来就是单例，这样似乎更加合理
    protected Logger logger = LogManager.getLogger(getClass());

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        /**
         * 自动转换日期类型的字段格式
         */
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        /**
         * 防止XSS攻击
         */
        binder.registerCustomEditor(String.class, new StringEscapeEditor());
    }

    /**
     * 获取当前登录用户对象
     *
     * @return {ShiroUser}
     */
    public ShiroUser getShiroUser() {
        return (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * 获取当前登录用户id
     *
     * @return {Long}
     */
    public Long getUserId() {
        return this.getShiroUser().getId();
    }

    /**
     * 获取当前登录用户名
     *
     * @return {String}
     */
    public String getStaffName() {
        return this.getShiroUser().getName();
    }

    /**
     * 获取当前登录用户公司代码
     *
     * @return {String}
     */
    public String getCompanyCode() {
        return this.getShiroUser().getCompanyCode();
    }

    /**
     * 请求错误返回
     *
     * @param code 返回码
     * @param msg 消息
     * @return {Object}
     */
    public Map<String, Object> renderError(Integer code, String msg) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        return result;
    }

    /**
     * 请求成功返回
     *
     * @param code 返回码
     * @param msg 消息
     * @return {Object}
     */
    public Map<String, Object> renderSuccess(Integer code, String msg) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        return result;
    }

    /**
     * 请求成功返回
     *
     * @param code 返回码
     * @param msg 消息
     * @return {Object}
     */
    public Map<String, Object> renderSuccess(Integer code, String msg, Object data) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        result.put("data", data);
        return result;
    }
    
    public String getbaseUrl(HttpServletRequest request){
 	   String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/";
 	   return baseUrl;//"http://120.25.194.209:8080/";
    }
    
    public String getRootPath(){
    	PropertiesLoader p = new PropertiesLoader("/config/application.properties");
    	return p.getProperty("file.upload.pathroot");
    }
    
    public Map<String,Object> getProLine(Integer id){
    	Map<String,Object> lineMap = null;
    	Dictionary dictionary = dictionaryService.selectById(id);
		if(dictionary!=null){
			lineMap = new HashMap<String,Object>();
			lineMap.put("id", dictionary.getId());
			lineMap.put("name", dictionary.getDicValue());
		}
    	return lineMap;
    }
    
    public Map<String,Object> getUserInfo(Integer userId){
    	Map<String,Object> userMap = null;
    	User user = userService.selectById(userId);
		if(user!=null){
			userMap = new HashMap<String,Object>();
			userMap.put("id", user.getId());
			userMap.put("name", user.getName());
		}else{
			userMap = new HashMap<String,Object>();
			userMap.put("id", "");
			userMap.put("name", "");
		}
    	return userMap;
    }
    
    public List<Map<String,Object>> getNotifys(String ids){
    	List<Map<String, Object>> notifysList  = null;
    	if(ids!=null){
    		User user = null;
    		Map<String,Object> userMap = null;
    		String[] notifyIds = ids.split(",");
    		notifysList  = new ArrayList<Map<String, Object>>();
    		for(int i=0;i<notifyIds.length;i++){
    			user = userService.selectById(Integer.parseInt(notifyIds[i]));
    			if(user!=null){
    				userMap = new HashMap<String,Object>();
    				userMap.put("id", user.getId());
    				userMap.put("name", user.getName());
    				notifysList.add(userMap);
    			}
    		}
    	}
		return notifysList;
    }
    
//    public static void main(String[] agrs){
//    	PropertiesLoader p = new PropertiesLoader("/config/application.properties");
//    	System.out.println("user==>"+p.getProperty("db.master.user"));
//    }
}
